<template>
	<view class="login">
		<!-- avatar -->
		<template v-if="!isTel">
			<view class="avatar fui-flex__center">
				<button style="border: none;" class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" plain>
					<view class="avatar-ab">
						<fui-icon name="picture" color="#fff"></fui-icon>
					</view>
					<fui-avatar :src="avatarUrl" size="large"></fui-avatar>
				</button>
			</view>
			<view class="content" style="margin: 400rpx 32rpx 0;">
				<view class="choose-nickname-row">
					<view class="fui-flex__between mb-30">
						<!-- <view class="" style="width: 10%;">
							<u-icon name="man-add" color="#799A43" size="40"></u-icon>
						</view> -->
						<input v-model="nickName" @input="inputName" type="nickname" placeholder="点击输入昵称"
							@blur="inputName" @focus="inputName" style="width: 100%;" />
					</view>
				</view>
			</view>
			<view class="btn-box fui-flex__center" style="margin: 0 32rpx;">
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
					style="width: 354rpx;height: 56rpx;background-color: #d9bb8c;color:#333;line-break: 56rpx;border-radius: 50rpx;"
					v-if="!isPhone && !userInfo.phoneNumber">
					<text class="font-24">获取手机号</text>
				</button>
				<button @click="submit" style="width: 354rpx;height: 56rpx;background-color: #d9bb8c;color:#333;line-break: 56rpx;border-radius: 50rpx;"
					v-if="isPhone && userInfo.phoneNumber">
					<text class="font-24">登录</text>
				</button>
			</view>
		</template>
		<template v-if="isTel">
			<view class="avatar fui-flex__center">
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" plain>
					<fui-avatar :src="avatarUrl" size="large"></fui-avatar>
				</button>
			</view>
			<view class="content" style="margin: 400rpx 32rpx 0;">
				<view class="choose-nickname-row">
					<view class="fui-flex__between mb-30">
						<!-- <view class="" style="width: 10%;">
							<u-icon name="man-add" color="#799A43" size="40"></u-icon>
						</view> -->
						<input v-model="nickName" @input="inputName" type="nickname" placeholder="点击输入昵称"
							@blur="inputName" @focus="inputName" style="width: 100%;" />
					</view>
				</view>
			</view>
			<view class="content my-32">
				<view class="choose-nickname-row" style="border: 1rpx solid #d9bb8c;border-radius: 50rpx;">
					<view class="fui-flex__between">
						<!-- <view class="" style="width: 10%;">
							<u-icon name="phone" color="#799A43" size="40"></u-icon>
						</view> -->
						<input v-model="phoneNumber" type="number" placeholder="请输入手机号" style="width: 100%;border: none;" />
						<view class="">
							<view style="width: 130rpx;font-size: 24rpx;" @click="getCode">{{ codeText }}</view>
						</view>
						<!-- <u-verification-code ref="uCode" @change="codeChange"></u-verification-code> -->
						<uv-code ref="uCode" @change="codeChange"></uv-code>
					</view>
				</view>
			</view>
			<view class="content" style="margin: 0 32rpx;">
				<view class="choose-nickname-row">
					<view class="fui-flex__between">
						<!-- <view class="" style="width: 10%;">
							<u-icon name="android-fill" color="#799A43" size="40"></u-icon>
						</view> -->
						<input v-model="verificationCode" type="number" placeholder="请输入验证码"
							style="width: 100%;" />
					</view>
				</view>
			</view>
			<view class="btn-box fui-flex__between" style="margin: 0 32rpx;">
				<button @click="phoneLoginNumber" style="width: 354rpx;height: 56rpx;background-color: #d9bb8c;color:#333;line-break: 56rpx;border-radius: 50rpx;">切换身份
				</button>
			</view>
		</template>
		<!-- <view class="flex justify-end items-end zm-mx-46 zm-mt-40" @tap="isTel = !isTel">
			{{ isTel ? '微信登录' : '手机号登录' }}
		</view> -->
	</view>
</template>

<script>
	import Apis from '@/common/fui-apis.js'
	export default {
		data() {
			return {
				avatarUrl: 'https://giftcard-1258726836.cos.ap-beijing.myqcloud.com/2024-02-23/1708703167050_login_icon.png',
				userInfo: {},
				isPhone: false,
				nickName: '',
				phoneNumber: '',
				verificationCode: '',
				isTel: false,
				isGift: false,
				codeText: '获取验证码'
			}
		},
		onLoad(option) {
			uni.login({
				provider: 'weixin',
				success: (res) => {
					Apis.login({
						code: res.code
					}).then(res1 => {
						console.log("res",res1);
						this.userInfo = res1.data;
						if (this.userInfo.phoneNumber) {
							this.isPhone = true
							uni.setStorageSync('openId', res1.data.openId);
							uni.setStorageSync('token', res1.data.token);
							uni.setStorageSync('userInfo', this.userInfo)
							this.$t.tip('登录成功，两秒后自动跳转')
							setTimeout(()=>{
								uni.navigateBack()
							},2000)
						} else {
							this.isPhone = false
							uni.setStorageSync('openId', res1.data.openId);
							uni.setStorageSync('token', res1.data.token);
						}
						if (this.userInfo.imagePath != null) {
							this.avatarUrl = this.userInfo.imagePath
						}
						// uni.setStorageSync('userInfo', this.userInfo)
						// uni.switchTab({
						// 	url: '/pages/tabbar/index/index'
						// });
						// this.$t.tip('登录成功，两秒后自动跳转')
						// setTimeout(()=>{
						// 	uni.navigateBack()
						// },2000)
					})
				},
				fail: err => {
					console.log('login fail:', err)
				}
			})

			if (option.info) {
				this.isSend = JSON.parse(decodeURIComponent(option.info))
			}
			if (uni.getStorageSync('giftId')) {
				this.isGift = true;
			}
			if (option?.isTel == 1){
				this.isTel = true;
				uni.setNavigationBarTitle({title:"切换身份"})
			}
		},
		methods: {
			// 验证码获得焦点事件
			codeVer() {
				let that = this;
				uni.getClipboardData({
					success: (res) => {
						that.verificationCode = res.data;
					}
				})
			},
			/* 获取验证码 */
			codeChange(text) {
				this.codeText = text;
			},

			getCode() {
				let that = this;
				let re = /^1\d{10}$/;
				if (!this.phoneNumber) return this.$t.tip('请输入手机号');
				if (!re.test(this.phoneNumber)) return this.$t.tip('请输入正确的手机号');
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					uni.login({
						provider: 'weixin',
						success: (res) => {
							Apis.sendVerificationCode({
								code: res.code,
								phoneNumber: that.phoneNumber
							}).then(res => {
								uni.hideLoading();
								that.$refs.uCode.start();
							})
						}
					})
					
				} else {
					this.$t.tip('倒计时结束后再发送');
				}
			},
			// 手机号登录
			phoneLoginNumber() {
				let that = this;
				uni.login({
					provider: 'weixin',
					success: async (res) => {
						Apis.phoneLoginNumber({
							code: res.code,
							phoneNumber: this.phoneNumber,
							verificationCode: this.verificationCode,
							imagePath: this.avatarUrl,
							name: this.nickName
						}).then(rex => {
							uni.setStorageSync('openId', rex.data.openId);
							uni.setStorageSync('token', rex.data.token);
							Apis.updateClient({
								imagePath: rex.data.imagePath,
								phone: rex.data.phoneNumber,
								name: rex.data.nickName,
								id: rex.data.userId
							}).then( rez => {
								that.userInfo = rez.data;
								that.userInfo.userId = that.userInfo.id;
								uni.setStorageSync('userInfo', that.userInfo)
								uni.showToast({
									title: '登录成功',
									icon: 'none'
								})
								uni.switchTab({
									url: '/pages/tabbar/index/index'
								});
								// await this.$ut.sleep(800)
								// if (that.isGift) {
								// 	uni.navigateBack();
								// } else {
								// 	if (!that.isSend) {
								// 		that.$ut.route('pages/index/index', {}, 'reLaunch');
								// 	} else {
								// 		uni.setStorageSync("giftId",that.isSend);
								// 		await this.$ut.sleep(800)
								// 		// 推广页
								// 		that.$ut.route(
								// 			'pages/index/commponents/sendTuiguang/sendTuiguang', {}, 'reLaunch')
								// 	}
								// }
								
							}).catch(err => {
								uni.showToast({
									title: err.message,
									icon: 'none'
								})
							})
						})
					}
				})

			},
			// 模板
			getMethod() {
				// #ifdef MP-WEIXIN
				wx.requestSubscribeMessage({
					tmplIds: ['9xLpOkbMsIXJGFN4Toe8btmjLIibT1ibMunbSCsBBLI'],
					success(res) {
						console.log(res)
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				this.$t.tip('请在微信环境下运行')
				// #endif
			},
			// 头像
			onChooseAvatar(e) {
				var uploadTask = uni.uploadFile({
					url: 'https://giftcard.qi-shop.cn/api/uploadFile/uploadOne', //仅为示例，非真实的接口地址
					filePath: e.detail.avatarUrl,
					name: 'file',
					success: (res) => {
						let obj = JSON.parse(res.data)
						console.log(JSON.parse(res.data))
						this.avatarUrl = obj.data;
					}
				});
			},
			// 用户名
			inputName(e) {
				this.nickName = e.detail.value
			},
			// 手机号
			getPhoneNumber(e) {
				console.log(e);
				Apis.getPhone({
					code: e.detail.code
				}).then(res => {
					this.userInfo.phoneNumber = res.data.phone_info.phoneNumber;
					uni.setStorageSync('userInfo', this.userInfo)
					this.$t.tip('登录成功，两秒后自动跳转')
					setTimeout(()=>{
						uni.navigateBack()
					},2000)
				}).catch(err => {
					this.$t.tip('获取手机号失败')
				})
			},
			async submit() {
				// #ifdef MP-WEIXIN
				const _this = this
				_this.login();
				return false;
				uni.getSetting({
					withSubscriptions: true,
					success(res) {
						if (!res.subscriptionsSetting.mainSwitch) {
							//后台封禁了
							//引导用户打开权限
							uni.showModal({
								title: '请在通知管理中开启接收通知的权限',
								success(res) {
									if (res.confirm) {
										uni.openSetting({})
									} else if (res.cancel) {
										uni.showToast({
											title: '您尚未开启接收通知的权限',
											icon: 'none'
										})
									}
								},
							})
						} else { //未封禁，则触发订阅消息
							wx.requestSubscribeMessage({
								tmplIds: ['9xLpOkbMsIXJGFN4Toe8btmjLIibT1ibMunbSCsBBLI'],
								success(res) {
									_this.login()
								}
							})
						}
					},
				})
				// #endif
				// #ifndef MP-WEIXIN
				this.$t.tip('请在微信环境下运行')
				// #endif
				// let user = uni.getStorageSync('userInfo');
				// || !this.PhoneCode || !localStorage.get('imgUrl')


			},
			login() {
				if (!this.nickName) {
					uni.showToast({
						title: '请将数据填写完整',
						icon: 'none'
					})
					return
				}
				Apis.updateClient({
					imagePath: this.avatarUrl,
					phone: this.userInfo.phoneNumber,
					name: this.nickName,
					id: this.userInfo.userId
				}).then(res => {
					this.userInfo = res.data;
					this.userInfo.userId = this.userInfo.id;
					uni.setStorageSync('userInfo', this.userInfo)
					setTimeout(() => {
						uni.showToast({
							title: '登录成功',
							icon: 'none'
						})
						uni.switchTab({
							url: '/pages/tabbar/index/index'
						});
						// if (this.isGift) {
						// 	//uni.setStorageSync('giftId', this.isSend)
						// 	// 推广页
						// 	this.$ut.route(
						// 		'pages/index/commponents/sendTuiguang/sendTuiguang', {
						// 			info: null
						// 	})
						// } else {
						// 	this.$ut.route('pages/index/index', {}, 'reLaunch');
						// }
					}, 800)
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err.message,
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page{
		background-color: #f2f2f2;
	}
	input{
		font-size: 24rpx;
	}
	.login {
		height: 100vh;
		width: 100%;
		background-color: #f2f2f2;
	}

	.avatar {
		width: 100%;
		padding-top: 316rpx;

		.avatar-wrapper {
			width: 180rpx;
			height: 160rpx;
			border: 1px solid rgba(0,0,0,0);
			// background-color: #fff;
			position: relative;
			.avatar-ab{
				position: absolute;
				width: 128rpx;
				height: 128rpx;
				border-radius: 50%;
				background-color: rgba(0, 0, 0, .3);
				z-index: 4;
				text-align: center;
				line-height: 128rpx;
			}

			.avatar {
				width: 100%;
				height: 100%;
			}
		}
	}

	.content {
		margin-top: 12rpx;
	}

	.choose-nickname-row {
		width: 354rpx;
		margin: 0 auto;
		// border-bottom: 1px solid #c5c5c5;
	}

	.btn-box {
		margin-top: 12rpx;
	}
	button {
		line-height: 56rpx;
		font-size: 28rpx;
		&::after{
			border: 1px solid rgba(0,0,0,0);
		}
	}
	input{
		width: 354rpx;
		height: 56rpx;
		text-align: center;
		line-height: 56rpx;
		border-radius: 50rpx;
		border: 1rpx solid #d9bb8c;
	}
</style>